<?php
namespace App\Traits;

use Illuminate\Support\Facades\Log;

trait ResponseFormat
{

    /**
     * @param $data
     * @param int $status
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function success($data, $status = 0,$msg='success')
    {

        return response([
            'status' => $status,
            'msg' => $msg,
            'data' => $data
        ]);
    }


    /**
     * @param $status int 返回码
     * @param $msg
     * @param array $args 替换占位符的参数，如果消息固定默认为空
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function error($status, $msg = '', $args = [])
    {
        if (empty($msg)) {
            $msg = config("error.{$status}") ?: '';
        }

        return response([
            'status' => $status,
            'msg' => $this->makeMsg($msg, $args)
        ]);
    }


    /**
     * json response for success
     * @param $data
     * @param int $status
     * @return \Illuminate\Http\JsonResponse
     */
    public function jsonSuccess($data, $status = 0)
    {
        return response()->json([
            'status' => $status,
            'msg' => 'success',
            'data' => $data
        ]);
    }

    /**
     * json response for error
     *
     * @param $status
     * @param string $msg
     * @param array $args
     * @return \Illuminate\Http\JsonResponse
     */
    public function jsonError($status, $msg = '', $args = [])
    {
        $this->handleInternalError($status, $msg, $args);
        return response()->json([
            'status' => $status,
            'msg' => $msg
        ]);
    }

    public function jsonException(\Exception $e, $code = '', $msg = '')
    {
        if (app()->bound('sentry') && 'local' !== env('APP_ENV')) {
            app('sentry')->captureException($e);
        }
        if ($code && $msg) {
            return $this->jsonError($code, $msg);
        }
        return ('local' == env('APP_ENV') && Str::start($e->getCode(), '3')) ? $this->jsonError($e->getCode(), $e->getMessage()) : $this->jsonError(100001, '内部服务器错误,请稍后重试');
    }

    /**
     *  错误信息打log
     * @param $statusCode
     * @param $msg
     * @param $args
     */
    protected function handleInternalError($statusCode, $msg, $args)
    {
        if ($statusCode == 100001) {
            Log::error($msg, $args);
        }
        return;
    }

    protected function makeMsg($msg = '', $args = [])
    {
        return $args ? sprintf($msg, ...$args) : $msg;
    }

}